using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace EmraldClient
{
  /// <summary>Being applied to container adds 
  ///   "select all text when <see cref="TextBox"/> got focus" behavior
  ///   to every <see cref="TextBox"/></summary>
  public class SelectAllOnFocusBehavior : Behavior<UIElement>
  {
    protected override void OnAttached()
    {
      base.OnAttached();
      AssociatedObject.GotKeyboardFocus += HandleKeyboardFocus;
      AssociatedObject.GotMouseCapture += HandleMouseCapture;
    }

    protected override void OnDetaching()
    {
      base.OnDetaching();
      AssociatedObject.GotKeyboardFocus -= HandleKeyboardFocus;
      AssociatedObject.GotMouseCapture -= HandleMouseCapture;
    }

    private static void HandleKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
    {
      var txt = e.NewFocus as TextBox;
      if (txt != null)
        txt.SelectAll();
    }

    private static void HandleMouseCapture(object sender, MouseEventArgs e)
    {
      var txt = e.OriginalSource as TextBox;
      if (txt != null)
        txt.SelectAll();
    }
  }

  public class FocusOnLoadBehavior : Behavior<FrameworkElement>
  {
    protected override void OnAttached()
    {
      AssociatedObject.Loaded += OnLoaded;
    }

    protected override void OnDetaching()
    {
      AssociatedObject.Loaded -= OnLoaded;
    }

    private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
    {
      AssociatedObject.Focus();
    }
  }
}